package com.css.apps.base.user.action.leader.action;

import java.util.ArrayList;
import java.util.List;

import com.css.apps.base.common.provider.json.OrgJsonProvider;
import com.css.apps.base.user.action.UserAction;
import com.css.apps.base.user.leader.model.LeaderSecretary;
import com.css.db.query.QueryCache;
import com.css.util.ListUtil;
import com.css.util.Messages;
import com.css.util.StringHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class GetSecretary extends UserAction {

	private String leaderId, lsType;
	private String tree, selected;
	
	@SuppressWarnings("unchecked")
	@Override
	protected String userGo() {
		if (StringHelper.isAnyEmpty(leaderId, lsType)) {
			setMessage(Messages.getString("systemMsg.fieldEmpty"));
			return ERROR;
		}
		boolean isSecretary = "secretary".equals(lsType) ? true : false,
				isBranchDept = "branchDept".equals(lsType) ? true : false;
		List<String> selectedIds = new ArrayList<>(), chkDisabled = new ArrayList<>();
		List<LeaderSecretary> lsList = new QueryCache("from LeaderSecretary").list();
		if (ListUtil.isLstNotEmpty(lsList)) {
			for (LeaderSecretary ls : lsList) {
				if (isSecretary) {
					String secretaryId = ls.getSecretaryId();
					if (leaderId.equals(ls.getLeaderId())) {
						selectedIds.add(secretaryId);
					} else {
						chkDisabled.add(secretaryId);
					}
				} else if (isBranchDept) {
					String branchDeptId = ls.getLeaderBranchDeptId(), _leaderId = ls.getLeaderId();
					if (leaderId.equals(_leaderId)) {
						selectedIds.add(ls.getLeaderBranchDeptId());
					} else {
						chkDisabled.add(branchDeptId);
					}
				}
			}
		}
		if (StringHelper.isNotEmpty(selected)) {
			JSONArray arr = JSONArray.fromObject(selected);
			if (arr != null && !arr.isEmpty()) {
				for (Object o : arr) {
					if (isSecretary) {
						selectedIds.add(((JSONObject) o).getString("secretaryId"));
					} else if (isBranchDept) {
						selectedIds.add(((JSONObject) o).getString("branchDeptId"));
					}
				}
			}
		} else {
			
		}
		OrgJsonProvider json = new OrgJsonProvider();
		if ("secretary".equals(lsType)) {
			tree = json.getOrgUserTree(true, selectedIds, chkDisabled).toString();
		} else if ("branchDept".equals(lsType)) {
			tree = json.getOrgCheckbox(selectedIds, false, chkDisabled).toString();
		}
		return SUCCESS;
	}

	public String getLeaderId() {
		return leaderId;
	}

	public void setLeaderId(String leaderId) {
		this.leaderId = leaderId;
	}

	public String getTree() {
		return tree;
	}

	public void setTree(String tree) {
		this.tree = tree;
	}

	public String getLsType() {
		return lsType;
	}

	public void setLsType(String lsType) {
		this.lsType = lsType;
	}

	public String getSelected() {
		return selected;
	}

	public void setSelected(String selected) {
		this.selected = selected;
	}

}
